import json
import logging
from datetime import datetime

from django.http import JsonResponse
from django.views import View

from lapi_app.models.testcase_model.testcase import Testcase
from lapi_app.models.testcase_model.testcase_tree import Menu
from lapi_app.view.testcase_view.updateJson import update_yapi

logger = logging.getLogger('django')


class Upload_case(View):

    def post(self, request, *args, **kwargs):
        body = json.loads(request.body)
        dicts = body["content"]
        user_id = body["user_id"]
        pid = body["pid"]
        # 接口需要用的数据
        case_list = []

        try:
            if body["upload_type"] == "postman":
                for key in dicts['item']:
                    if 'item' in key.keys():
                        for i in key['item']:
                            if "item" in i:
                                for p in i["item"]:
                                    try:
                                        keys = json.dumps(p)
                                        req = json.loads(keys)
                                        # 获取接口名称
                                        name = req["name"]
                                        request = json.loads(json.dumps(req["request"]))

                                        # 获取请求方法
                                        # 1:get 2.post 3:put 4:delete
                                        method = ''
                                        if request["method"] == 'GET':
                                            method = 1
                                        elif request["method"] == 'POST':
                                            method = 2
                                        elif request["method"] == 'PUT':
                                            method = 3
                                        elif request["method"] == 'DELETE':
                                            method = 4

                                        # 获取请求url
                                        url = request['url']

                                        path = url['path']

                                        path_value = ''
                                        for n in range(0, len(path)):
                                            path_value += "/" + path[n]

                                        # 获取params
                                        if "query" in url.keys():
                                            params = url['query']
                                        else:
                                            params = []

                                        # 获取参数类型
                                        body_type = ''
                                        if 'body' in request:
                                            b = json.dumps(request["body"])
                                            body = json.loads(b)
                                            if body['mode'] == 'formdata':
                                                body_type = 1
                                            elif body['mode'] == 'raw':
                                                body_type = 2
                                            elif body['mode'] == 'urlencoded':
                                                body_type = 3
                                        else:
                                            body_type = 4

                                        # 获取请求头
                                        headers = {}
                                        h = json.dumps(request["header"])
                                        header = json.loads(h.replace("\"", '"'))
                                        for item in header:
                                            headers[item['key']] = item['value']

                                        # 获取请求体
                                        raw = {}
                                        if 'body' in request:
                                            body = json.loads(json.dumps(request["body"]))
                                            if body['mode'] == 'raw':
                                                raw = body['raw'].replace("\"", '"')
                                            elif body['mode'] == 'urlencoded':
                                                raw = {}
                                                for data_body in body['urlencoded']:
                                                    c = data_body['key']
                                                    d = data_body['value']
                                                    data_body2 = {c: d}
                                                    raw.update(data_body2)
                                            elif body['mode'] == 'formdata':
                                                raw = {}
                                                for data_body in body['formdata']:
                                                    e = data_body['key']
                                                    f = data_body['value']
                                                    data_body4 = {e: f}
                                                    raw.update(data_body4)
                                        else:
                                            raw = {}

                                        # 获取更新时间
                                        updatetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                                        # 获取s更新时间
                                        createtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                                        # 最终数据
                                        case_json = {
                                            "name": name,
                                            "method": method,
                                            "url": path_value,
                                            "header": headers,
                                            "params": params,
                                            "body_type": body_type,
                                            "body": raw,
                                            "updatetime": updatetime,
                                            "createtime": createtime
                                        }
                                        case_list.append(case_json)
                                    except Exception as e:
                                        print(str(e))
                            elif 'request' in i:
                                try:
                                    keys = json.dumps(i)
                                    req = json.loads(keys)

                                    # 获取接口名称
                                    name = req["name"]

                                    request = json.loads(json.dumps(req["request"]))
                                    # 获取请求方法
                                    # 1:get 2.post 3:put 4:delete
                                    method = ''
                                    if request["method"] == 'GET':
                                        method = 1
                                    elif request["method"] == 'POST':
                                        method = 2
                                    elif request["method"] == 'PUT':
                                        method = 3
                                    elif request["method"] == 'DELETE':
                                        method = 4

                                    # 获取请求url
                                    url = request['url']
                                    path = url['path']
                                    path_value = ''
                                    for n in range(0, len(path)):
                                        path_value += "/" + path[n]

                                    # 获取params
                                    if "query" in url.keys():
                                        params = url['query']
                                    else:
                                        params = []

                                    # 获取参数类型
                                    body_type = ''
                                    if 'body' in request:
                                        b = json.dumps(request["body"])
                                        body = json.loads(b)
                                        if body['mode'] == 'formdata':
                                            body_type = 1
                                        elif body['mode'] == 'raw':
                                            body_type = 2
                                        elif body['mode'] == 'urlencoded':
                                            body_type = 3
                                    else:
                                        body_type = 4

                                    # 获取请求头
                                    headers = {}
                                    h = json.dumps(request["header"])
                                    header = json.loads(h.replace("\"", '"'))
                                    for item in header:
                                        headers[item['key']] = item['value']

                                    # 获取请求体
                                    raw = {}
                                    if 'body' in request:
                                        b = json.dumps(request["body"])
                                        body = json.loads(b)
                                        if body['mode'] == 'raw':
                                            raw = json.loads(body['raw'].replace("\"", '"'))
                                        elif body['mode'] == 'urlencoded':
                                            raw = {}
                                            for data_body in body['urlencoded']:
                                                c = data_body['key']
                                                d = data_body['value']
                                                data_body2 = {c: d}
                                                raw.update(data_body2)
                                        elif body['mode'] == 'formdata':
                                            raw = {}
                                            for data_body in body['formdata']:
                                                e = data_body['key']
                                                f = data_body['value']
                                                data_body4 = {e: f}
                                                raw.update(data_body4)
                                    else:
                                        raw = {}

                                    # 获取更新时间
                                    updatetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                                    # 获取s更新时间
                                    createtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                                    # 最终数据
                                    case_json = {
                                        "name": name,
                                        "method": method,
                                        "url": path_value,
                                        "header": headers,
                                        "params": params,
                                        "body_type": body_type,
                                        "body": raw,
                                        "updatetime": updatetime,
                                        "createtime": createtime
                                    }
                                    case_list.append(case_json)
                                except Exception as e:
                                    print(str(e))

                    elif 'request' in key:
                        try:
                            keys = json.dumps(key)
                            req = json.loads(keys)
                            # 获取接口名称
                            name = req["name"]
                            request = json.loads(json.dumps(req["request"]))
                            # 获取请求方法
                            # 1:get 2.post 3:put 4:delete
                            method = ''
                            if request["method"] == 'GET':
                                method = 1
                            elif request["method"] == 'POST':
                                method = 2
                            elif request["method"] == 'PUT':
                                method = 3
                            elif request["method"] == 'DELETE':
                                method = 4
                            # 获取请求url
                            url = request['url']
                            path = url['path']
                            path_value = ''
                            for n in range(0, len(path)):
                                path_value += "/" + path[n]
                                # 获取params
                                if "query" in url.keys():
                                    params = url['query']
                                else:
                                    params = []
                            # 获取参数类型
                            body_type = ''
                            if 'body' in request:
                                b = json.dumps(request["body"])
                                body = json.loads(b)
                                if body['mode'] == 'formdata':
                                    body_type = 1
                                elif body['mode'] == 'raw':
                                    body_type = 2
                                elif body['mode'] == 'urlencoded':
                                    body_type = 3
                                else:
                                    body_type = 4

                            # 获取请求头
                            headers = {}
                            h = json.dumps(request["header"])
                            header = json.loads(h.replace("\"", '"'))
                            for item in header:
                                headers[item['key']] = item['value']

                            # 获取请求体
                            raw = {}
                            if 'body' in request:
                                b = json.dumps(request["body"])
                                body = json.loads(b)
                            if body['mode'] == 'raw':
                                raw = json.loads(body['raw'].replace("\"", '"'))
                            elif body['mode'] == 'urlencoded':
                                raw = {}
                                for data_body in body['urlencoded']:
                                    c = data_body['key']
                                    d = data_body['value']
                                    data_body2 = {c: d}
                                    raw.update(data_body2)
                            elif body['mode'] == 'formdata':
                                raw = {}
                                for data_body in body['formdata']:
                                    e = data_body['key']
                                    f = data_body['value']
                                    data_body4 = {e: f}
                                    raw.update(data_body4)
                            else:
                                raw = {}

                            # 最终数据
                            case_json = {
                                "name": name,
                                "method": method,
                                "url": path_value,
                                "header": headers,
                                "params": params,
                                "body_type": body_type,
                                "body": raw
                            }
                            case_list.append(case_json)
                        except Exception as e:
                            print(str(e))
                result_list = []
                result_list.extend(case_list)
                result = []
                for case in result_list:
                    c = Testcase.objects.create(t_name=case["name"], t_method=case["method"],
                                                t_url=case["url"], t_params=case["params"], t_type=case["body_type"],
                                                t_header=case["header"], t_body=case["body"],
                                                update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                                create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                                t_user_id=user_id)
                    m = Menu.objects.create(label=case["name"], pid=pid, type=2, m_user_id=user_id, testcase_id=c.id)
                    menu_list = {"label": case["name"], "pid": pid, "type": 2, "id": m.id}
                    result.append(menu_list)
                return JsonResponse({
                    "code": 200,
                    "message": "导入接口成功",
                    "case": case_list,
                    "result": result
                })
            elif body["upload_type"] == "yapi":
                yapi_list = update_yapi(dicts)
                result = []
                for i in yapi_list:
                    pid_menu = Menu.objects.create(label=i["project_name"], type=1, m_user_id=user_id, pid=pid)
                    parent_dict = {
                        "id": pid_menu.id,
                        "pid": pid,
                        "type": 1,
                        "label": i["project_name"]
                    }
                    if i["children"]:
                        children = []
                        for j in i["children"]:
                            testcase = Testcase.objects.create(
                                t_name=j["name"], t_method=j["method"],
                                t_header={"Content-Type": "application/json"}, t_body=j["body"],
                                t_params=j["params"], t_url=j["url"], t_user_id=user_id
                            )
                            menu = Menu.objects.create(label=j["name"], type=2, m_user_id=user_id, pid=pid_menu.id, testcase_id=testcase.id)
                            children_dict = {
                                "id": menu.id,
                                "pid": pid_menu.id,
                                "type": 2,
                                "label": i["project_name"],
                            }
                            children.append(children_dict)
                        parent_dict.update({"children": children})
                    result.append(parent_dict)
                return JsonResponse({
                    "code": 200,
                    "message": "导入接口成功",
                    "result": result
                })
        except Exception as e:
            return JsonResponse({
                "code": 100,
                "message": "文件异常，导入失败",
                "info": str(e)
            })
